package com.yeyks.aop;

import com.yeyks.common.exception.ServiceException;
import com.yeyks.common.utils.IpUtil;
import com.yeyks.common.utils.Splitters;
import com.yeyks.commonReference.append.redis.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author fuchangshuai
 * @date 2019/05/07 10:52
 * 基于自定义注解实现token验证
 */
@Component
@Slf4j
public class WhiteListInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private RedisService redisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String ip = IpUtil.getIpAddr(request);
        String ips = redisService.getValue("ipWhiteList");
        if (null == ips) {
            return true;
        }
        List<String> ipLists = Splitters.splitToString(ips, Splitters.COMMA);
        if (!ipLists.contains(ip)) {
            log.info("Not on the white list");
            log.info("ip地址为：{}", ip);
            throw new ServiceException("无权访问");
        }
        return true;
    }
}
